/* 
 * File:   JClient.cpp
 * Author: johnneyshi
 * 
 * Created on 2013年1月28日, 下午1:43
 */

#include "JClient.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include "JException.h"

JClient::JClient(std::string _ip,int _port) : clientIP(_ip),clientPort(_port)
{
    
}

void JClient::Bind(std::string _ip, int _port)
{
    clientIP = _ip;
    clientPort = _port;
}
//JClient::JClient(const JClient& orig) {
//}

JClient::~JClient() {
}

//void JClient::Bind()
//{
//    connFd = socket(AF_INET,SOCK_STREAM,0);
//    if(connFd < 0)
//    {
//        throw JException("JClient::JClient socket error.");
//    }
//    if(clientIP == "" && clientPort == 0)
//    {
//        
//    }
//    else
//    {
//        struct sockaddr_in clientAddr;
//        bzero(&clientAddr,sizeof(sockaddr_in));
//        clientAddr.sin_family = AF_INET;
//        inet_aton(this->clientIP.c_str(),&clientAddr.sin_addr);
//        clientAddr.sin_port = htons(this->clientPort);
//        if(bind(connFd,(struct sockaddr*)&clientAddr,sizeof(sockaddr_in)) < 0)
//        {
//            throw JException("JClient::JClient bind error.");
//        }
//    }
//}

void JClient::Connect(std::string _ip, int _port)
{
    //Bind
    connFd = socket(AF_INET,SOCK_STREAM,0);
    if(connFd < 0)
    {
        throw JException("JClient::JClient socket error.");
    }
    if(clientIP == "" && clientPort == 0)
    {
        
    }
    else
    {
        struct sockaddr_in clientAddr;
        bzero(&clientAddr,sizeof(sockaddr_in));
        clientAddr.sin_family = AF_INET;
        inet_aton(this->clientIP.c_str(),&clientAddr.sin_addr);
        clientAddr.sin_port = htons(this->clientPort);
        if(bind(connFd,(struct sockaddr*)&clientAddr,sizeof(sockaddr_in)) < 0)
        {
            throw JException("JClient::JClient bind error.");
        }
    }
    
    //Connect
    struct sockaddr_in serverAddr;
    bzero(&serverAddr,sizeof(sockaddr_in));
    serverAddr.sin_family = AF_INET;
    inet_aton(_ip.c_str(),&(serverAddr.sin_addr));
    serverAddr.sin_port = htons(_port);
    if(connect(this->connFd,(struct sockaddr*)&serverAddr,sizeof(sockaddr_in)) < 0)
    {
        throw JException("JClient::Connect connect error.");
    }
}

int JClient::GetConnFd()
{
    return this->connFd;
}

std::string JClient::GetClientIP()
{
    return this->clientIP;
}

int JClient::GetClientPort()
{
    return this->clientPort;
}

std::string JClient::GetServerIP()
{
    return this->serverIP;
}

int JClient::GetServerPort()
{
    return this->serverPort;
}

void JClient::Send(const char* msg, int size)
{
    write(this->connFd,msg,size);
}

int JClient::Recv(char* msg, int size)
{
    return read(this->connFd,msg,size);
}
